package com.borrowed.book.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.borrowed.book.book.constant.BookConstant;
import com.borrowed.book.book.domain.SCouponDto;
import com.borrowed.book.book.domain.SelectUserCouponInDto;
import com.borrowed.book.coupon.entity.SCoupon;
import com.borrowed.book.coupon.entity.SCouponUser;
import com.borrowed.book.coupon.service.SCouponService;
import com.borrowed.book.coupon.mapper.SCouponMapper;
import com.borrowed.book.coupon.service.SCouponUserService;
import com.borrowed.book.system.exception.CommonException;
import com.borrowed.book.system.util.DayUtil;
import com.borrowed.book.user.domain.SUser;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
*优惠券服务
*/
@Service
public class SCouponServiceImpl extends ServiceImpl<SCouponMapper, SCoupon> implements SCouponService{
    @Autowired
    private SCouponUserService couponUserService;

    /**
     * 新增优惠券
     * @param coupon
     * @return
     * @throws CommonException
     */
    @Override
    public boolean addCoupon(SCoupon coupon) throws CommonException{
        if(coupon.getStartTime()!=null&&coupon.getStartTime().before(new Date())){
            throw  new CommonException("优惠券发放开始时间不能早于当前时间");
        }else{
            this.baseMapper.insert(coupon);
            return true;
        }
    }

    /**
     * 修改优惠券
     *
     * @param coupon
     * @return
     * @throws CommonException
     */
    @Override
    public boolean updateCoupon(SCoupon coupon) throws CommonException {
        if(coupon.getStartTime()!=null&&coupon.getStartTime().before(new Date())){
            throw  new CommonException("优惠券发放开始时间不能早于当前时间");
        }else{
            this.baseMapper.updateById(coupon);
            return true;
        }
    }


    /**
     * 删除优惠券
     * @param id
     * @return
     * @throws CommonException
     */
    @Override
    public boolean deleteCoupon(Long id) throws CommonException {
        Boolean deleteFlag=true;
        SCoupon coupon=this.getById(id);
        //已经开始发放并且有用户领用了的优惠券不能删除
        if(coupon.getStartTime()!=null&&coupon.getStartTime().before(new Date())){
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("coupon_id",id);
            List<SCouponUser> couponUserList=couponUserService.list(queryWrapper);
            if(couponUserList.size()>0){
                deleteFlag=false;
            }
        }
        if(deleteFlag){
           this.baseMapper.deleteById(id);
           return true;
        }else{
            throw new CommonException("已开始发放并且已有用户领用了的优惠券不能删除");
        }
    }

    /**
     * 新人用户自动创建优惠券
     *
     * @param openid
     */
    @Override
    public void createNewuserCoupon(String openid) {
        List<SCoupon> couponList=this.list();
        for(SCoupon coupon:couponList){
            //新人年会员优惠券
            if(BookConstant.COUPON_TYPE_TWO.equals(coupon.getCouponType())){
                Date validEndTime;
                //计算优惠券使用结束日期
                if(BookConstant.VALID_TYPE_TWO.equals(coupon.getValidType())) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + coupon.getValidDays());
                    calendar= DayUtil.setLastHourMinite(calendar);
                    validEndTime=calendar.getTime();
                }else{
                    validEndTime=coupon.getValidEndTime();
                }
                SCouponUser couponUser=new SCouponUser();
                couponUser.setOpenid(openid);
                couponUser.setCreateTime(new Date());
                couponUser.setValidStartTime(new Date());
                couponUser.setCouponStatus(BookConstant.COUPON_STATUS_UNUSE);//待使用
                couponUser.setCouponId(coupon.getId());
                couponUser.setValidEndTime(validEndTime);
                couponUser.setFaceValue(coupon.getFaceValue());
                couponUserService.save(couponUser);
                //增加coupon表的takeCount
                coupon.setTakeCount(coupon.getTakeCount()+1);
                this.updateById(coupon);
            }
        }
    }

    /**
     * 购买会员给用户创建快递优惠券
     *
     * @param endTime
     * @param openid
     * @param number
     */
    @Override
    public void createMemberCardExpressCoupon(Date endTime, String openid, Integer number) {
        List<SCouponUser> list=new ArrayList<>();
        for(int i=0;i<number;i++){
            List<SCoupon> couponList=this.list();
            for(SCoupon coupon:couponList){
                if(BookConstant.COUPON_TYPE_THREE.equals(coupon.getCouponType())) {
                    Date validEndTime = endTime;
                    SCouponUser couponUser = new SCouponUser();
                    couponUser.setOpenid(openid);
                    couponUser.setCreateTime(new Date());
                    couponUser.setValidStartTime(new Date());
                    couponUser.setCouponStatus(BookConstant.COUPON_STATUS_UNUSE);//待使用
                    couponUser.setCouponId(coupon.getId());
                    couponUser.setValidEndTime(validEndTime);
                    couponUser.setFaceValue(coupon.getFaceValue());
                    list.add(couponUser);
                    //增加coupon表的takeCount
                    coupon.setTakeCount(coupon.getTakeCount()+1);
                    this.baseMapper.updateById(coupon);
                }
            }
        }
        couponUserService.saveBatch(list);
    }

    /**
     * 小程序端根据用户查询优惠券
     *
     * @param param
     */
    @Override
    public List<SCouponDto> selectUserCoupon(SelectUserCouponInDto param) {
        SUser sysUser = (SUser) SecurityUtils.getSubject().getPrincipal();
        Map<String,Object> map=new HashMap<>();
        map.put("openid",sysUser.getOpenid());
        map.put("couponStatus",param.getCouponStatus());
        map.put("couponType",param.getCouponType());
        List<SCouponDto> couponList=this.baseMapper.selectUserCouponList(map);
        for(SCouponDto coupon:couponList) {
            if (BookConstant.COUPON_STATUS_UNUSE.equals(coupon.getCouponStatus())) {
                coupon.setRemainDays(DayUtil.daysBetween(new Date(), coupon.getValidEndTime()));
            }
        }
        return couponList;
    }

}
